import React, { Component } from 'react'
import { MyScroll } from '../../components/index'
import mineStyle from './mine.module.scss'
import { arr } from '../../mock'

// 模拟异步接口
const createData = ({ page = 1, size = 10 }) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(arr.slice((page - 1) * size, page * size))
    }, 3000)
  })
}

/**
 * 划分组件：
 * 1. 子组件告诉父组件 下拉 上拉
 * 2. 父组件接收数据 处理数据，渲染dom
 * 3. 数据在父组件中，请求，但是有延时，子组件必须等待 父组件的所有的数据都到位之后，才能new
 */

export default class Mine extends Component {
  constructor(props) {
    super(props)
    this.state = {
      page: 1,
      size: 5,
      list: [],
      flag: false,
    }
  }

  fetchList = async ({ page = this.state.page, size = this.state.size }) => {
    const list = await createData({ page, size })
    console.log('didmount-请求数据', list)
    return list
  }

  componentDidMount() {
    this.fetchList({}).then((list) => {
      this.setState({ list, flag: true })
    })
  }

  loading = true
  render() {
    return (
      <div className="mine-wrapper" style={{ height: '100%' }}>
        <MyScroll
          // flag 告诉父组件什么new
          flag={this.state.flag}
          // 下拉刷新
          handlePullingDown={(func) => {
            this.fetchList({}).then((res) => {
              func('我请求完了')
            })
          }}
          // 上拉加载
          handlePullingUp={(func) => {
            if (this.loading) {
              this.setState({
                page: this.state.page + 1,
              })
              this.loading = false
              this.fetchList({ page: this.state.page }).then((list) => {
                this.loading = true
                this.setState({ list: [...this.state.list, ...list] })
                console.log('tong', this.state.list)
                func('我请求完了')
              })
            }
          }}
        >
          {this.state.list.map((item) => {
            return (
              <div key={item.id} className={mineStyle['bs-item']}>
                {item.productName}
              </div>
            )
          })}
        </MyScroll>
      </div>
    )
  }
}
